<?php

namespace app\admin\controller\select;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Queue;


/**
 * 产品出入库信息管理
 *
 * @icon fa fa-circle-o
 */
class Storage extends Backend
{

    /**
     * Storage模型对象
     * @var \app\admin\model\select\Storage
     */
    protected $model = null;
    protected $noNeedRight = ['specs'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\select\Storage;
        $this->view->assign("isFearQueryList", $this->model->getIsFearQueryList());

    }

    /**
     * 退库
     */
    public function refundOrderInfo($ids){
        Db::startTrans();
        try{
            $storage_info_model = new \app\common\model\Storage();

            $this->deletedFallBack('',$ids);

            $update             = array(
                'oi_is_deleted'  => 1,
                'oi_refund_time'   => time() //退库时间
            );
            $where['oi_id']      = array('in',$ids);
            $storage_info = $storage_info_model->getList($where);
            $where['oi_is_deleted'] = 0;
            $storage_res  = $storage_info_model->isUpdate(true)->save($update,$where);
            //需要处理订单数量的减少
            $order_model  = new \app\admin\model\select\Order();
            $order_ids    = array_column($storage_info,'oi_order_id');
            $update      = array(
                'o_has_refund'     => 1,
                'o_refund_time'    => time()
            );
            $where         = [];
            $where['o_id'] = ['in' , $order_ids];
            $order_res = $order_model->isUpdate(true)->update($update,$where);
            if(!$storage_res || !$order_res){
                throw new Exception('退库失败');
            }

            //处理是否清账
            $account_record_model = new \app\admin\model\account\Record();
            foreach ( $order_ids as $val ){
                $account_record_model->saveOrderSettled($val);
            }
            Db::commit();
            $this->success('退库成功');
        }catch ( Exception $e ){
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

    public function out(){
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        $ret = $this->index(1);
        return $ret;
    }


    public function in(){
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        $ret = $this->index(2);
        return $ret;
    }


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function refundinfo()
    {
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where(['oi_enterprise_id'=>$this->auth->es_id,'oi_refund_time'=>['<>',0],'oi_warehouse'=>1])
            ->order($sort, $order)
            ->paginate($limit);
        $data = $list->items();
        foreach ($data as &$val){
            //查询供货商
            $update_storage = json_decode($val['oi_update_storage'],true);
            if($update_storage){
                $storage_id     = key($update_storage);
                $out_storage    = $this->model->find($storage_id);
                $val['supply_name'] = $out_storage['oi_user_name'];
            }else{
                $val['supply_name'] = '';
            }

        }

        $result = ['total' => $list->total(), 'rows' => $data];
        return json($result);
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index($storage_type = 1)
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where(['oi_enterprise_id'=>$this->auth->es_id,'oi_is_deleted'=>0,'oi_warehouse'=>$storage_type])
            ->order($sort, $order)
            ->paginate($limit);
        $data = $list->items();
        foreach ($data as &$val){
            //查询供货商
            $update_storage = json_decode($val['oi_update_storage'],true);
            if($update_storage){
                $storage_id     = key($update_storage);
                $out_storage    = $this->model->find($storage_id);
                $val['supply_name'] = $out_storage['oi_user_name'];
            }else{
                $val['supply_name'] = '';
            }

        }

        $result = ['total' => $list->total(), 'rows' => $data];
        return json($result);
    }



    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {

        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $params['oi_es_id'] =  $this->auth->es_id;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $specs_arr = array(
                '单瓶' => array(
                    'oi_unit' => '瓶',
                    'oi_bottle_num' => 1,
                ),
                '整箱' => array(
                    'oi_unit' => '箱',
                    'oi_bottle_num' => 1,
                ),
                '2瓶/箱' => array(
                    'oi_unit' => '箱',
                    'oi_bottle_num' => 2,
                ),
                '4瓶/箱' => array(
                    'oi_unit' => '箱',
                    'oi_bottle_num' => 4,
                ),
                '6瓶/箱' => array(
                    'oi_unit' => '箱',
                    'oi_bottle_num' => 6,
                ),
                '12瓶/箱' => array(
                    'oi_unit' => '箱',
                    'oi_bottle_num' => 12,
                ),
            );
            if($params['oi_specs']){
                $params['oi_unit']= $specs_arr[$params['oi_specs']]['oi_unit'];
                $params['oi_bottle_num']= $specs_arr[$params['oi_specs']]['oi_bottle_num'];
            }
            $cate_model = new \app\admin\model\select\Category();
            $cate       = $cate_model->find($params['oi_cate_id']);
            $params['oi_cate_name'] = $cate['c_title'];
            $result = $row->allowField(true)->save($params);


            //处理是否清账
            $account_record_model = new \app\admin\model\account\Record();
            $account_record_model->saveOrderSettledByStorageId([$ids]);

            //加入同步出入库信息队列
            $data = ['ids' =>implode(',',[$ids])];

            $jobHandlerClassName  = 'app\common\job\synchronizationStorage';
            // 当前任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName     = "synchronizationStorageQueue";
            // // 即时执行
            Queue::push($jobHandlerClassName, $data, $jobQueueName);
            // // 延迟 2 秒执行
            // $isPushed = Queue::later( 2, $jobHandlerClassName, $jobDataArr, $jobQueueName);
            // // 延迟到 2017-02-18 01:01:01 时刻执行
            // $time2wait = strtotime('2017-02-18 01:01:01') - strtotime('now');
            // $isPushed = Queue::later($time2wait,$jobHandlerClassName, $jobDataArr, $jobQueueName);
           // $isPushed = Queue::later(3600 * 24 * $day, $jobHandlerClassName, $data, $jobQueueName);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function editall($ids = null)
    {
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('ids', $ids);
            return $this->view->fetch();
        }

        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {

            $specs_arr = array(
                '单瓶' => array(
                    'oi_unit' => '瓶',
                    'oi_bottle_num' => 1,
                ),
                '整箱' => array(
                    'oi_unit' => '箱',
                    'oi_bottle_num' => 1,
                ),
                '2瓶/箱' => array(
                    'oi_unit' => '箱',
                    'oi_bottle_num' => 2,
                ),
                '4瓶/箱' => array(
                    'oi_unit' => '箱',
                    'oi_bottle_num' => 4,
                ),
                '6瓶/箱' => array(
                    'oi_unit' => '箱',
                    'oi_bottle_num' => 6,
                ),
                '12瓶/箱' => array(
                    'oi_unit' => '箱',
                    'oi_bottle_num' => 12,
                ),
            );
            if($params['oi_specs']){
                $data['oi_specs'] = $params['oi_specs'];
                $data['oi_unit']= $specs_arr[$params['oi_specs']]['oi_unit'];
                $data['oi_bottle_num']= $specs_arr[$params['oi_specs']]['oi_bottle_num'];
            }
            if($params['oi_cate_id']){
                $data['oi_cate_id'] = $params['oi_cate_id'];
                $cate_model = new \app\admin\model\select\Category();
                $cate       = $cate_model->find($params['oi_cate_id']);
                $data['oi_cate_name'] = $cate['c_title'];
            }
            if($params['oi_price']){
                $data['oi_price'] = $params['oi_price'];
            }

            if($params['year']){
                $data['oi_year'] = $params['year'];
            }

            if($params['is_fear_query'] != -1){
                $data['oi_is_fear_query'] = $params['is_fear_query'];
            }
            $result = $this->model->isUpdate(true)->save($data,['oi_id'=>['in',$ids]]);


            //处理是否清账
            $account_record_model = new \app\admin\model\account\Record();
            $account_record_model->saveOrderSettledByStorageId($ids);

            //加入同步出入库信息队列
            $data = ['ids' =>$ids];

            $jobHandlerClassName  = 'app\common\job\synchronizationStorage';
            // 当前任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName     = "synchronizationStorageQueue";
            // 即时执行
            Queue::push($jobHandlerClassName, $data, $jobQueueName);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }


    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            $ids_arr = [];
            foreach ($list as $item) {
                $count += $item->save(['oi_is_deleted'=>1]);
                $ids_arr[] = $item->oi_id;
            }
            if($list[0]['oi_warehouse'] == 1){
                $this->deletedFallBack('',$ids_arr);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


    public function specs(){
        $searchValue = $this->request->param('searchValue');
        if($searchValue){
            return json(['list' => [0 => ['id' => $searchValue, 'name' => $searchValue]], 'total' => 1]);
        }
        $specs = [
           0 => [
               'id' => '单瓶',
               'name' => '单瓶',
           ],
            1 => [
                'id' => '2瓶/箱',
                'name' => '2瓶/箱'
            ],
            2 => [
                'id' => '4瓶/箱',
                'name' => '4瓶/箱'
            ],
            3 => [
                'id' => '6瓶/箱',
                'name' => '6瓶/箱'
            ],
            4 => [
                'id' => '12瓶/箱',
                'name' => '12瓶/箱'
            ],
            5 => [
                'id' => '整箱',
                'name' => '整箱'
            ],
        ];
        return json(['list' => $specs, 'total' => 6]);
    }

}
